//var service = angular.module('starter.services', []);
service.factory('missionFactory',['$q',function($q){

    var ORDER_FIELDS = ['remark','payway','uid','address','messioned','orderid','total','paytime','approvaldate','type','finalAmount','description','areaId','shopId','status','goods','location'];
    var ORDER_TYPE = {retrunGoods:11,exchangeGoods:12};
    var Mission = AV.Object.extend('Mission');
    var CourierCart = AV.Object.extend('CourierCart');
    var Product = AV.Object.extend('Product');
    var Order = AV.Object.extend('Order');

    //售后订单的类型;
    var RETURN_ORDER_TYPE = [11,12];
    //列表需要的状态码
    var ORDER_STATUS = [2500,3000,4000];

    //售后订单列表需要的状态码
    var RETURNORDER_STATUS = [3000,4000];

    var get0Time = function(){
        var today = new Date();
        today.setHours(0);
        today.setMinutes(0);
        today.setSeconds(0);
        today.setMilliseconds(0);
        return today.getTime()/1000;
    }
    return {
        PAGE_SIZE:20,
        getMissionInfo:function(page){
            var storage = window.localStorage;
            var uid = storage.getItem("uid");
            var queryMission = new AV.Query(Mission);
            queryMission.skip(this.PAGE_SIZE * (page - 1));
            queryMission.equalTo('uid',uid+'');
            queryMission.equalTo('status',1);
            queryMission.descending('updatedAt');
            queryMission.limit(this.PAGE_SIZE);
            return queryMission.find();
        },
        getMissionInfoGroupByOrderStatus:function(page,orders){
            var q = $q.defer();
            var storage = window.localStorage;
            var uid = storage.getItem("uid");
            var queryMission = new AV.Query(Order);
            queryMission.skip(this.PAGE_SIZE * (page - 1));
            queryMission.equalTo('messionedUser',uid+'');
            queryMission.descending('updatedAt');
            queryMission.notContainedIn('type',[11,12]);
            if(orders.type === "mhcx"){
                queryMission.contains('orderid',orders.orderid);
            }
            if(orders.type === "afljMISSIOIN"){
                queryMission.equalTo("status",parseInt(orders.status));  //"status",orders.status
            }
            queryMission.limit(this.PAGE_SIZE);
            /*if(orders.type === "mhcx"){
                //queryMission.contains('orderid',orders.orderid);
                AV.Query.doCloudQuery("select * from Order where messionedUser=? and orderid like '%?%'order by updatedAt desc limit ?,?",[uid+"",orders.orderid+"",this.PAGE_SIZE * (page - 1),this.PAGE_SIZE],
                    {
                        success: function(result){
                            q.resolve(result.results);
                        },
                        error: function(error){
                            q.reject(error);
                        }
                    });
            }else if(orders.type === "afljMISSIOIN"){
                AV.Query.doCloudQuery("select * from Order where messionedUser=? and status=? order by -orderid,+updatedAt limit ?,?",[uid+"",parseInt(orders.status),this.PAGE_SIZE * (page - 1),this.PAGE_SIZE],
                    {
                        success: function(result){
                            q.resolve(result.results);
                        },
                        error: function(error){
                            q.reject(error);
                        }
                    });
            }*/
            return queryMission.find();
        },
        searchMissions:function(orderid){
            var storage = window.localStorage;
            var uid = storage.getItem("uid");
            var queryMission = new AV.Query(Mission);
            queryMission.equalTo('uid',uid+'');
            queryMission.equalTo('status',1);
            queryMission.descending('updatedAt');
            queryMission.contains('orderid',orderid);
            return queryMission.find();
        },
        getOrderInfo:function(orderid){
            var queryOrder = new AV.Query(Order);
            queryOrder.equalTo('orderid',orderid);
            return queryOrder.first();
        },
        getMissionCount:function(){
            var storage = window.localStorage;
            var uid = storage.getItem("uid");
            var queryMission = new AV.Query(Mission);
            queryMission.equalTo('uid',uid+'');
            queryMission.equalTo('status',1);
            return queryMission.count();
        },
        updateMissionInfo:function(orderid,info){
            var q = $q.defer();
            var storage = window.localStorage;
            var uid = storage.getItem("uid");
            var queryMission = new AV.Query(Mission);
            queryMission.equalTo('uid',uid+'');
            queryMission.equalTo('orderid',orderid+'');
            queryMission.equalTo('status',1);
            queryMission.first().then(function(res){
                if(res){
                    res.save(info).then(function(){
                        q.resolve({code:0});
                    }).catch(function(err){
                        q.reject({code:1});
                    });
                }else{
                    q.reject({code:1});
                }
            });
            return q.promise;
        },
        insertCourier:function(list){
            var q = $q.defer();
            console.log('============');
            console.log(list);
            var storage = window.localStorage;
            var uid = storage.getItem("uid");

            var queryCourier = new AV.Query(CourierCart);
            queryCourier.equalTo('uid',uid+'');
            queryCourier.equalTo('pid',list.pid+'');
            queryCourier.equalTo('psid',list.psid+'');
            queryCourier.first().then(function(res){
                if(res){
                    var oldNum = res.get('num');
                    var newNum = list.num ;
                    res.save({num:parseInt(oldNum+(parseInt(newNum)-parseInt(oldNum)))}).then(function(data){
                        q.resolve({code:0,data:data});
                    }).catch(function(err){
                        q.reject({code:1});
                    });
                }else{
                    q.reject({code:1});
                }
            });
            return q.promise;
        },
        getAllCountByStatus:function(){
            var storage = window.localStorage;
            var uid = storage.getItem("uid");
            var query = new AV.Query(Mission);
            query.equalTo('uid',uid+'');
            query.equalTo('status',1);
            return query.count();
        },
        getCountByStatus:function(MISSION_TYPE,MISSION_TYPE_NAME){
            var q = $q.defer();
            var returnData=[];
            var storage = window.localStorage;
            var uid = storage.getItem("uid");
            var query = new AV.Query(Order);
            query.equalTo('messionedUser',uid+'');
            query.notContainedIn('type',[11,12]);
            async.eachOfSeries(MISSION_TYPE,function(value,keys,callback){
                query.equalTo('status',parseInt(value));
                query.count().then(function(count){
                    returnData.push({type:keys,name:MISSION_TYPE_NAME[keys],count:count});
                    callback(null,returnData );
                });
            },function(err){
                if(err){
                    q.reject(err);
                }else{
                    console.log(111111111);
                    console.log(returnData)
                    q.resolve(returnData);
                }
            });
            return q.promise;
        },
        getSalesOrder:function(type,uid,page,typeName){
            var queryOrder = new AV.Query(Order);
            //if(type===ORDER_TYPE[typeName]){
            //    var status = [2500,3000];
            //}else{
            //    var status = [2500,3000,4000];
            //}
            var status = [7000,8000];
            queryOrder.skip(this.PAGE_SIZE * (page - 1));
            queryOrder.select(ORDER_FIELDS);
            queryOrder.equalTo('type',parseInt(type));
            queryOrder.containedIn('status',status);
            queryOrder.equalTo('messionedUser',uid+"");
            queryOrder.limit(this.PAGE_SIZE);
            return queryOrder.find();
        },
        getCountOfSales:function(type,uid,typeName){
            var queryOrder = new AV.Query(Order);
            //if(parseInt(type)===parseInt(ORDER_TYPE[typeName])){
            //    var status = [2500,3000];
            //}else{
            //    var status = [2500,3000,4000];
            //}
            var status = [7000,8000];
            queryOrder.select(ORDER_FIELDS);
            queryOrder.equalTo('type',parseInt(type));
            queryOrder.containedIn('status',status);
            queryOrder.equalTo('messionedUser',uid+"");
            return queryOrder.count();
        },
        getCountInMission:function(options){
            var q = $q.defer();
            var storage = window.localStorage;
            var uid = storage.getItem("uid");
            async.auto({
                //获取退货数量
                getTHCount:function(callback){
                    var queryOrder = new AV.Query(Order);
                    var status = [7000,8000];
                    queryOrder.select(ORDER_FIELDS);
                    queryOrder.equalTo('type',ORDER_TYPE.retrunGoods);
                    queryOrder.containedIn('status',status);
                    queryOrder.equalTo('messionedUser',uid+"");
                    queryOrder.count().then(function(count){
                        callback(null,count);
                    }).catch(function(err){
                        callback(null,0);
                    });
                },
                //获取换货数量
                getHHCount:function(callback){
                    var queryOrder = new AV.Query(Order);
                    var status = [7000,8000];
                    queryOrder.select(ORDER_FIELDS);
                    queryOrder.equalTo('type',ORDER_TYPE.exchangeGoods);
                    queryOrder.containedIn('status',status);
                    queryOrder.equalTo('messionedUser',uid+"");
                    queryOrder.count().then(function(count){
                        callback(null,count);
                    }).catch(function(err){
                        callback(null,0);
                    });
                },
                //获取订单池子数量
                getCZCount:function(callback){
                    var todayZeroTime = get0Time();
                    var tomZeroTime = todayZeroTime + 60 * 60 * 24;

                    var myOrder = new AV.Query(Order);
                    myOrder.select(ORDER_FIELDS);
                    myOrder.containedIn('status',RETURNORDER_STATUS);
                    myOrder.containedIn('type',RETURN_ORDER_TYPE);
                    myOrder.containedIn('areaId',options.areaId);
                    myOrder.notEqualTo('messioned',true);
                    myOrder.addDescending('status');
                    myOrder.addAscending('paytime');

                    var normalOrder = new AV.Query(Order);
                    normalOrder.select(ORDER_FIELDS);
                    normalOrder.containedIn('status',RETURNORDER_STATUS);
                    normalOrder.containedIn('type',RETURN_ORDER_TYPE);
                    normalOrder.containedIn('areaId',options.areaId);
                    normalOrder.notEqualTo('messioned',true);
                    normalOrder.addDescending('status');
                    normalOrder.addAscending('paytime');

                    var monthOrder = new AV.Query(Order);
                    monthOrder.select(ORDER_FIELDS);
                    monthOrder.containedIn('status',RETURNORDER_STATUS);
                    monthOrder.containedIn('type',RETURN_ORDER_TYPE);
                    monthOrder.lessThan('bookdate',''+tomZeroTime);//小于第二天
                    monthOrder.greaterThan('bookdate',''+todayZeroTime);//大于凌晨
                    monthOrder.containedIn('areaId',options.areaId);
                    monthOrder.notEqualTo('messioned',true);
                    monthOrder.addDescending('status');
                    monthOrder.addAscending('paytime');

                    var query = AV.Query.or(myOrder,normalOrder, monthOrder);
                    query.count().then(function(count){
                        callback(null,count);
                    }).catch(function(err){
                        callback(null,0);
                    });
                }
            },function(err,results){
                if(err){
                    q.reject({returnGoodsCount:results.getTHCount,exchangeGoodsCount:results.getHHCount,chiziCount:results.getCZCount});
                }else{
                    q.resolve({returnGoodsCount:results.getTHCount,exchangeGoodsCount:results.getHHCount,chiziCount:results.getCZCount});
                }
            });
            return q.promise;
        }
    }

}]);